package com.example.result.player

import android.content.ComponentName
import android.net.Uri
import android.util.Log
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.focusable
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.SideEffect
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalView
import androidx.compose.ui.viewinterop.AndroidView
import androidx.media3.common.MediaItem
import androidx.media3.common.Player
import androidx.media3.session.MediaController
import androidx.media3.session.SessionToken
import androidx.media3.ui.PlayerView
import com.google.common.util.concurrent.MoreExecutors

//define permission in composable fun
@Composable
fun CheckPermission(permissions: Array<String>, onGranted: () -> Unit, onDined: () -> Unit) {
    val getPermission = rememberLauncherForActivityResult(
        ActivityResultContracts.RequestMultiplePermissions()
    ) { result ->
        Log.e("PlayerScreen", "${result.keys}:" + result.toString())
        if (result.isEmpty() || result.any { !it.value }) {
            onDined()
        } else {
            onGranted()
        }
    }
    SideEffect {
        Log.e("PlayerScreen", permissions.reduce { acc, s -> acc + "\n" + s })
        getPermission.launch(permissions)
    }
}


@Composable
fun PlayerScreen(uri: Uri) {
    val context = LocalView.current.context
    val playerView = remember {
        PlayerView(context)
    }
    DisposableEffect(playerView, uri) {
        val sessionToken =
            SessionToken(context, ComponentName(context, PlaybackService::class.java))
        val controllerFuture = MediaController.Builder(context, sessionToken).buildAsync()
        controllerFuture.addListener(
            {
                // Call controllerFuture.get() to retrieve the MediaController.
                // MediaController implements the Player interface, so it can be
                // attached to the PlayerView UI component.
                val player = controllerFuture.get()
                player.setMediaItem(MediaItem.fromUri(uri))

                playerView.player = player
            },
            MoreExecutors.directExecutor()
        )
        onDispose {
            MediaController.releaseFuture(controllerFuture)
        }
    }

    AndroidView(
        modifier = Modifier
            .focusable(),
        factory = { playerView },
        update = { playerView ->
            playerView.player?.let { player: Player ->
                if (!player.isPlaying) {
                    player.play()
                }
            }

            Log.d("PlayerScreen", uri.toString())
        }
    )
}